#!/usr/bin/env bash
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.

# shellcheck disable=SC2034
ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"

docker_image_exists() {
  docker image inspect "$1" >/dev/null 2>&1
  return $?
}

build_docker_images(){
    if docker_image_exists "nvidia/cuda:12.9.0-cudnn-runtime-ubuntu24.04"; then
        echo "docker image nvidia/cuda:12.9.0-cudnn-runtime-ubuntu24.04 exists."
    else
        # 通过代理下载基础的cuda镜像
        docker pull docker.m.daocloud.io/nvidia/cuda:12.9.0-cudnn-runtime-ubuntu24.04
        docker tag docker.m.daocloud.io/nvidia/cuda:12.9.0-cudnn-runtime-ubuntu24.04 nvidia/cuda:12.9.0-cudnn-runtime-ubuntu24.04
        docker rmi docker.m.daocloud.io/nvidia/cuda:12.9.0-cudnn-runtime-ubuntu24.04
    fi

    if docker_image_exists "kernelstudio/cuda-runtime:12.9.0"; then
        echo "docker image kernelstudio/cuda-runtime:12.9.0 exists."
    else
        # shellcheck disable=SC2028
        echo ""
        echo "build docker image kernelstudio/cuda-runtime:12.9.0"
        echo ""
        cd "${ROOT_DIR}/docker/images/cuda" || exit 1
        docker build -f ./Dockerfile -t kernelstudio/cuda-runtime:12.9.0 .
    fi

    if docker_image_exists "kernelstudio/cuda-liboffice-runtime:latest"; then
        echo "docker image kernelstudio/cuda-liboffice-runtime:latest exists."
    else
        # shellcheck disable=SC2028
        echo ""
        echo "build docker image kernelstudio/cuda-liboffice-runtime:latest"
        echo ""
        cd "${ROOT_DIR}/docker/images/liboffice" || exit 1
        docker build -f ./Dockerfile -t kernelstudio/cuda-liboffice-runtime:latest .
    fi

    if docker_image_exists "kernelstudio/document-server-runtime:latest"; then
        echo "docker image kernelstudio/document-server-runtime:latest exists."
    else
        # shellcheck disable=SC2028
        echo ""
        echo "build docker image kernelstudio/document-server-runtime:latest"
        echo ""
        cd "${ROOT_DIR}/docker/images/app" || exit 1
        docker build -f ./Dockerfile -t kernelstudio/document-server-runtime:latest .
    fi

    # shellcheck disable=SC2164
    cd "${ROOT_DIR}"
    docker build -f ./Dockerfile -t kernelstudio/document-server-app:latest .
}


main(){
    build_docker_images
}

main